/*
 * @Description 限制同源使用
 * @Author hanl
 * @Date 2024-06-17 16:14:09
 * @LastEditors hanl
 * @LastEditTime 2024-07-31 11:20:40
 */
import { ref } from "vue";
/** 通讯事件名称 */
export const BROADCAST_CHANNEL_NAME = "hlfine-test";

export type BroadcastChannelMessage<T> = {
  /** 事件类型 */
  type: string;
  /** 事件数据 */
  data: T;
};

export const useMessage = (initialization = false) => {
  const MessageMain = ref<BroadcastChannel | null>(null);

  const init = () => {
    MessageMain.value = new BroadcastChannel(BROADCAST_CHANNEL_NAME);
  };

  /** 发送广播信息 */
  const postMessage = <T>(message: BroadcastChannelMessage<T>) => {
    if (MessageMain.value) {
      console.log("发送广播信息:", message);

      MessageMain.value.postMessage(message);
    }
  };
  /** 接受广播信息 */
  const onMessage = <T>(callback?: (message: BroadcastChannelMessage<T>) => void) => {
    if (MessageMain.value) {
      MessageMain.value.onmessage = (e) => {
        console.log("接受广播信息:", e.data);
        callback && callback(e.data);
      };
    }
  };

  /** 关闭广播事件 */
  const onClose = () => {
    if (MessageMain.value) {
      MessageMain.value.close();
    }
  };

  if (initialization) {
    init();
  }

  return {
    BROADCAST_CHANNEL_NAME,
    MessageMain,
    init,
    postMessage,
    onMessage,
    onClose,
  };
};
